import React, { useEffect, useCallback, useState, useMemo } from 'react';
import { CircularProgress, Box, Button, Drawer, Stack, IconButton } from '@mui/material';
import { MaterialReactTable, useMaterialReactTable, MRT_ShowHideColumnsButton as ShowHideColumnsButton } from 'material-react-table';
import { getCrmRecordById, getCrmRecordFromSql } from "../../util/util";
import exportToExcel from '../../util/exportToExcel';
import { Clear, GetAppOutlined } from '@mui/icons-material';
import { useSnackbar } from '../customized/SnackbarProvider'; // 导入自定义的 hook
import { MRT_Localization_ZH_HANS as LocalizationZH } from 'material-react-table/locales/zh-Hans';


//生产发货通知单明细操作

const App = (pagedata) => {
    const [tabledata, setTabledata] = useState([]); // 用于存储获取的数据
    const [isloacked, setIsloacked] = useState(false); // 数据锁定状态
    const [crmdata, setCrmdata] = useState([]); // 用于存储CRM获取的数据
    const [productdata, setProductdata] = useState([]); // 用于存储获取的数据
    // const [deletedata, setDeletedata] = useState([]); // 用于存储删除的数据
    const [rowSelection, setRowSelection] = useState([]); // 用于存储选中的行
    const [loading, setLoading] = useState(true); // 用于控制加载状态
    const [loadingptable, setLoadingptable] = useState(true); // 用于控制加载状态
    const [openDrawer, setOpenDrawer] = useState(false); // 控制抽屉的显示与隐藏
    const openSnackbar = useSnackbar();


    const fetchData = useCallback(async () => {
        try {
            setLoading(true); // 设置加载状态为true
            console.log("pagedata", pagedata)
            const dataid = pagedata?.data?.EntityId[0];
            const entity = pagedata?.data?.Entity;
            const data = await getCrmRecordById(entity, dataid);
            console.log("data", data);
            if (data) {
                setCrmdata(data); // 将获取的数据存储到crmdata中
                let isloacked = data?.Locked__s || false;
                setIsloacked(isloacked);

                if (data?.LinkingModule8) {
                    let detaildata = data?.LinkingModule8;
                    console.log("detaildata", detaildata);
                    const filteredData = detaildata.filter(item =>
                        item?.Product !== null &&
                        item?.Product?.id !== null
                    ); // 过滤掉 Product_Name 为 null 或 id 为 null 的数据
                    setTabledata(filteredData); // 将获取的数据存储到tabledata中
                }
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoading(false); // 数据获取完成后，将加载状态设置为false
        }
    }, [pagedata]);



    useEffect(() => {
        window.ZOHO.CRM.UI.Resize({ height: "100%", width: "100%" })
        fetchData();
    }, [fetchData]);

    //获取产品
    const productsGet = async () => {
        setLoadingptable(true);
        try {
            let soids = crmdata?.Exportcontractnumberid; // 获取订单ID
            let soarray = soids.split(",");
            let idstring = soarray.map(item => `'${item}'`).join(', ');
            //, Chineseingredients, Total, Net_Total
            let sql = `select Parent_Id.id as pid, Parent_Id.AccountOrderNo as AccountOrderNo, Parent_Id.Subject as Subject, HSCode, ChinesePackagedesp, Productname, Chptrequirements_material, Chinesespecification, Volume, Nuofboxesinpg, Nuofboxeinnerbox, internalcode, Netweight, Packaginunit, List_Price, Unit, Brand, ShippingMark, field3, Product_Name.id as pdid, Product_Name.Product_Name as pname,Product_Name.Overseasfactorypurchaseprice as Purchaseunitprice, AccountprtNo, Cartonwidth, field, field2, field1, Description, Quantity, PSQty, SNQty, Packagingquantityperpg, Grossweight, W, NumberofCartons, Category, Englishname, Specification, Lengthofouterbox, Heightofouterbox, id from Ordered_Items where Parent_Id in (${idstring}) limit 2000`;

            let productresult = await getCrmRecordFromSql(sql);


            //可用数量为0
            //已被选择
            productresult.forEach(item => {
                const foundItem = tabledata.find(i => i.id1 === item.id);
                if (foundItem) {
                    item.selected = true;
                }
            });


            console.log("productresult", productresult);
            setProductdata(productresult);
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoadingptable(false);
        }
    };

    const handleSave = async () => {
        setLoading(true); // 显示加载状态
        try {
            // const dataid = crmdata.id;
            const dataname = crmdata.Name;
            // const olddetaildata = crmdata?.Ordered_Items;
            let requiredarray = []; //记录必填项数组
            let errorRows = [];  //记录箱数不为整数的行
            tabledata.forEach((item, index) => {
                delete item?.Sequence_Number;
                // delete item?.Parent_Id;
                delete item?.LinkingModule8_Serial_Number;
                let qty = item?.PurchaseQty;
                let packqty = item?.PackQty;
                if (isNaN(qty) || isNaN(qty) || qty < 0 || packqty < 0) {
                    requiredarray.push(index + 1); // Store 1-based index
                }
                console.log('packqty', packqty);

                if (packqty < 0 || packqty % 1 !== 0) {
                    errorRows.push(index + 1); // Store 1-based index
                }
            });
            // console.log('requiredarray',requiredarray);
            if (requiredarray.length > 0) {
                openSnackbar(`第${requiredarray.join(', ')}行箱数、数量不能为空或者0！`, 'error');
                return;
            };
            if (errorRows.length > 0) {
                openSnackbar(`第${errorRows.join(', ')}行箱数不是整数！`, 'error');
                return;
            };
            let datainfojson = [{
                "Name": dataname,
                // "id": dataid,
                "LinkingModule8": tabledata,
            }];
            console.log("datainfojson", JSON.stringify(datainfojson));
            let result_save = await window.ZOHO.CRM.API.upsertRecord({ Entity: "PSNotice", APIData: datainfojson, duplicate_check_fields: ["Name",], Trigger: ["workflow"] });
            console.log(JSON.stringify(result_save));
            await window.ZOHO.CRM.UI.Popup.closeReload();
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoading(false);  // 隐藏加载状态
        }
    };


    //合同明细的列配置
    const columns_product = [
        { accessorKey: 'pname', header: '商品库名称', minSize: 140, size: 140, enableEditing: false, },
        { accessorKey: 'AccountprtNo', header: '客户货号', minSize: 110, size: 110, enableEditing: false, },
        { accessorKey: 'Subject', header: '订单号', minSize: 110, size: 110, enableEditing: false, },
        { accessorKey: 'AccountOrderNo', header: '客户订单号', minSize: 150, size: 150, enableEditing: false, },
        { accessorKey: 'ShippingMark', header: '唛头', minSize: 80, size: 80, enableEditing: false, },
        { accessorKey: 'internalcode', header: '内部代码', minSize: 110, size: 110, enableEditing: false, },
        { accessorKey: 'Englishname', header: '英文品名', minSize: 100, enableEditing: false, },
        { accessorKey: 'Specification', header: '英文规格', minSize: 100, enableEditing: false, },
        // { accessorKey: 'List_Price', header: '单价', minSize: 90, size: 90, enableEditing: false, },
        // { accessorKey: 'Discount', header: '折扣', minSize: 90, size: 90, enableEditing: false, },
        { accessorKey: 'PSQty', header: '已生产数量', minSize: 130, size: 130, enableEditing: false, },
        { accessorKey: 'Quantity', header: '数量', minSize: 90, size: 90, enableEditing: false, },
        { accessorKey: 'NumberofCartons', header: '箱数', minSize: 90, size: 90, },
        { accessorKey: 'Packagingquantityperpg', header: '每箱装量', minSize: 90, size: 90, },
        // { accessorKey: 'Total', header: '金额', minSize: 100, size: 100, enableEditing: false, },
        // { accessorKey: 'Net_Total', header: '总计', minSize: 100, size: 100, enableEditing: false, },
        // { accessorKey: 'DomesticOrderAmount', header: '国内接单金额', minSize: 140, size: 140, },
        { accessorKey: 'Unit', header: '单位', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'Brand', header: '品牌', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'Nuofboxesinpg', header: '入数', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'Nuofboxeinnerbox', header: '内盒数', minSize: 120, size: 120, enableEditing: false, },
        { accessorKey: 'Lengthofouterbox', header: '长(CM)', minSize: 120, size: 120, enableEditing: false, },
        { accessorKey: 'Cartonwidth', header: '宽(CM)', minSize: 120, size: 120, enableEditing: false, },
        { accessorKey: 'Heightofouterbox', header: '高(CM)', minSize: 120, size: 120, enableEditing: false, },
        { accessorKey: 'Volume', header: '体积', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'Netweight', header: '净重(KG)', minSize: 120, size: 120, enableEditing: false, },
        { accessorKey: 'Grossweight', header: '毛重(KG)', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'field2', header: '总净重', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'field1', header: '总毛重', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'field', header: '总体积', minSize: 100, size: 100, enableEditing: false, },
        { accessorKey: 'Productname', header: '中文品名', minSize: 100, enableEditing: false, },
        { accessorKey: 'ChinesePackagedesp', header: '中文包装描述', minSize: 100, enableEditing: false, },
        { accessorKey: 'Chinesespecification', header: '中文规格', minSize: 100, enableEditing: false, },
        // { accessorKey: 'Chineseingredients', header: '中文成份', minSize: 100, enableEditing: false, },
        { accessorKey: 'Chptrequirements_material', header: '中文生产要求(材质)', minSize: 180, enableEditing: false, },
        { accessorKey: 'Category', header: '类别', minSize: 90, size: 90, enableEditing: false, },
        { accessorKey: 'Packaginunit', header: '包装单位', minSize: 90, size: 90, enableEditing: false, },
        { accessorKey: 'HSCode', header: 'HS编码', minSize: 100, enableEditing: false, },
        { accessorKey: 'field3', header: '商品备注', minSize: 100, enableEditing: true, },
    ];
    const totalPurchaseAmount = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.PurchaseAmount || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    const totalPurchaseQty = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.PurchaseQty || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    const totalTotalGrossweight = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.TotalGrossweight || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    const totalTotalNetweight = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.TotalNetweight || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    const totalTotalVolume = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.TotalVolume || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    const totalPackQty = useMemo(
        () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.PackQty || 0)), 0),
        [tabledata], // 确保在 data 变化时重新计算
    );
    //子表列配置
    const columns = useMemo(() => [
        { accessorKey: 'AccountOrderNo', header: '客户订单号', size: 120, minSize: 120, enableEditing: false },
        { accessorKey: 'Product.name', header: '产品编号', size: 130, minSize: 130, enableEditing: false },
        { accessorKey: 'AccountprtNo', header: '客户货号', size: 110, minSize: 110, enableEditing: false },
        { accessorKey: 'internalcode', header: '内部货号', size: 110, minSize: 110, enableEditing: false },
        { accessorKey: 'Productname', header: '中文品名', size: 180, minSize: 180, enableEditing: false },
        { accessorKey: 'Chinesespecification', header: '中文规格', size: 130, minSize: 130, enableEditing: false },
        {
            accessorKey: 'Chptrequirements_material', header: '中文生产要求(材质)', size: 250, minSize: 250, enableEditing: true,
            muiEditTextFieldProps: ({ cell, column, row, table }) => ({
                type: 'text',
                onBlur: (event) => {
                    tabledata[row.index][column.id] = event.target.value || "";
                    setTabledata([...tabledata]); // 更新表格数据
                },
            })
        },
        // { accessorKey: 'Chineseingredients', header: '中文成份', size: 130, minSize: 130, enableEditing: false },
        { accessorKey: 'Make', header: '品牌', size: 130, minSize: 130, enableEditing: false },
        { accessorKey: 'Englishname', header: '英文货名', size: 180, minSize: 180, enableEditing: false },
        { accessorKey: 'Specification', header: '英文规格', size: 130, minSize: 130, enableEditing: false },
        { accessorKey: 'Quantity', header: '数量(总)', size: 130, minSize: 130, enableEditing: false, enableSorting: false, },
        { accessorKey: 'NumberofCartons', header: '箱数(总)', size: 130, minSize: 130, enableEditing: false, enableSorting: false, },
        { accessorKey: 'Quantity_unused', header: '可用数量', size: 130, minSize: 130, enableEditing: false, enableSorting: false, },
        {
            accessorKey: 'PurchaseQty', header: '数量(此次)', size: 130, minSize: 130, enableEditing: true, enableSorting: false,
            muiEditTextFieldProps: ({ cell, row, table }) => ({
                type: 'number',
                required: true, // 设置必填
                onBlur: (event) => {
                    // console.log(table); // 打印表格实例
                    // console.log(row); // 打印表格实例
                    // console.log(table.getAllColumns()); // 打印表格实例
                    const qty = parseFloat(event.target.value) || 0; // Ensure it's a number

                    const index = cell.row.index;

                    tabledata[index]['PurchaseQty'] = qty;
                    let boxnum = (qty / (tabledata[index]['Packagingquantityperpg'] || 1)).toFixed(1);
                    tabledata[index]['PackQty'] = boxnum;

                    // Calculate other fields based on the new quantity
                    tabledata[index]['TotalVolume'] = (tabledata[index]['Volume'] * boxnum).toFixed(4);
                    tabledata[index]['TotalGrossweight'] = (tabledata[index]['Grossweight'] * boxnum).toFixed(4);
                    tabledata[index]['TotalNetweight'] = (tabledata[index]['Netweight'] * boxnum).toFixed(4);
                    tabledata[index]['PurchaseAmount'] = (qty * tabledata[index]['Purchaseunitprice']).toFixed(3);
                    const newTableData = [...tabledata];

                    setTabledata(newTableData);
                },
            }),
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalPurchaseQty.toFixed(2)}</Box>
                </Stack>
            ),
        },
        {
            accessorKey: 'PackQty', header: '箱数(此次)', size: 130, minSize: 130, enableEditing: true, enableSorting: false,
            muiEditTextFieldProps: ({ cell, row }) => ({
                type: 'number',
                required: true, // 设置必填
                onBlur: (event) => {
                    const boxnum = parseFloat(event.target.value) || 0; // Ensure it's a number

                    const index = cell.row.index;
                    tabledata[index]['PackQty'] = boxnum;

                    // Calculate other fields based on the new quantity
                    let qty = boxnum * (tabledata[index]['Packagingquantityperpg'] || 1).toFixed(0);
                    tabledata[index]['PurchaseQty'] = qty;
                    tabledata[index]['TotalVolume'] = (tabledata[index]['Volume'] * boxnum).toFixed(4);
                    tabledata[index]['TotalGrossweight'] = (tabledata[index]['Grossweight'] * boxnum).toFixed(4);
                    tabledata[index]['TotalNetweight'] = (tabledata[index]['Netweight'] * boxnum).toFixed(4);
                    tabledata[index]['PurchaseAmount'] = (qty * tabledata[index]['Purchaseunitprice']).toFixed(3);

                    const newTableData = [...tabledata];

                    setTabledata(newTableData);
                },
            }),
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalPackQty.toFixed(2)}</Box>
                </Stack>
            ),

        },
        { accessorKey: 'Packagingquantityperpg', header: '每箱数量', size: 130, minSize: 130, enableEditing: false },
        {
            accessorKey: 'Purchaseunitprice', header: '海外工厂采购价', size: 150, minSize: 150, enableEditing: true,
            muiEditTextFieldProps: ({ cell, row }) => ({
                type: 'number',
                required: true, // 设置必填
                onBlur: (event) => {
                    const index = cell.row.index;
                    const value = parseFloat(event.target.value) || 0; // Ensure it's a number
                    tabledata[index]['Purchaseunitprice'] = value;

                    tabledata[index]['PurchaseAmount'] = (value * tabledata[index]['PurchaseQty']).toFixed(3);
                    const newTableData = [...tabledata];

                    setTabledata(newTableData);
                },
            }),
        },
        {
            accessorKey: 'PurchaseAmount', header: '海外工厂采购金额', size: 180, minSize: 180, enableEditing: false,
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalPurchaseAmount.toFixed(3)}</Box>
                </Stack>
            ),
        },
        { accessorKey: 'Unit', header: '单位', size: 90, minSize: 90, enableEditing: false },
        { accessorKey: 'Nuofboxesinpg', header: '入数', size: 90, minSize: 90, enableEditing: false },
        { accessorKey: 'Nuofboxeinnerbox', header: '内盒数', size: 90, minSize: 90, enableEditing: false },
        { accessorKey: 'Packaginunit', header: '包装单位', size: 90, minSize: 90, enableEditing: false },
        { accessorKey: 'Lengthofouterbox', header: '长(CM)', size: 120, minSize: 120, enableEditing: false },
        { accessorKey: 'Cartonwidth', header: '宽(CM)', size: 120, minSize: 120, enableEditing: false },
        { accessorKey: 'Heightofouterbox', header: '高(CM)', size: 120, minSize: 120, enableEditing: false },
        { accessorKey: 'Volume', header: '体积（CBM）', size: 140, minSize: 140, enableEditing: false },
        { accessorKey: 'Netweight', header: '外箱净重(KG)', size: 140, minSize: 140, enableEditing: false },
        { accessorKey: 'Grossweight', header: '外箱毛重(KG)', size: 140, minSize: 140, enableEditing: false },
        { accessorKey: 'Category', header: '类别', size: 90, minSize: 90, enableEditing: false },
        {
            accessorKey: 'TotalGrossweight', header: '总毛重', size: 130, minSize: 130, enableEditing: false,
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalTotalGrossweight.toFixed(4)}</Box>
                </Stack>
            ),
        },
        {
            accessorKey: 'TotalNetweight', header: '总净重', size: 130, minSize: 130, enableEditing: false,
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalTotalNetweight.toFixed(4)}</Box>
                </Stack>
            ),
        },
        {
            accessorKey: 'TotalVolume', header: '总体积', size: 130, minSize: 130, enableEditing: false,
            Footer: () => (
                <Stack>
                    <Box color="warning.main">{totalTotalVolume.toFixed(4)}</Box>
                </Stack>
            ),
        },
    ], [tabledata, totalPurchaseAmount, totalPurchaseQty, totalTotalGrossweight, totalTotalNetweight, totalTotalVolume, totalPackQty]);


    //子表配置
    const table = useMaterialReactTable({
        columns: columns,
        data: tabledata ?? [],
        enableRowOrdering: true, // 行排序
        enablePagination: false, // 禁用分页
        enableColumnOrdering: true, // 列排序
        enableColumnFilters: false, // 列过滤
        enableStickyHeader: true, // 启用粘性表头
        localization: LocalizationZH, // 设置中文
        enableGlobalFilter: false, // 禁用全局过滤
        enableColumnResizing: true, // 启用列调整大小
        editDisplayMode: 'cell', // 编辑模式为单元格
        enableEditing: true,  // 启用编辑
        enableDensityToggle: false, // 禁用密度切换
        // enableRowOrdering: true, // 启用行排序
        enableSorting: false, // 禁用排序
        enableFullScreenToggle: false, // 禁用全屏按钮
        enableColumnPinning: true, // 启用列固定
        // getRowId: (row) => row.rowid, // 设置每行的唯一标识
        positionToolbarAlertBanner: 'bottom',   // 将工具栏警告横幅的位置设置为底部
        layoutMode: 'grid-no-grow', // 设置布局模式为网格，并且不增长
        initialState: {
            density: 'compact',
            columnPinning: { left: ['mrt-row-drag', 'mrt-row-actions', 'mrt-row-numbers', 'Product.name', 'AccountprtNo', 'internalcode'] },  //'mrt-row-actions',
        },
        muiTableContainerProps: {
            sx: {
                minHeight: '80vh', // 这里设置表格最大高度
                maxHeight: '80vh', // 这里设置表格最大高度
                overflowY: 'auto',  // 启用竖向滚动条
                overflowX: 'auto',  // 启用横向滚动条，横向滚动条默认显示
            },
        },
        muiTableHeadCellProps: ({ column }) => ({
            sx: {
                backgroundColor: 'rgb(244, 247, 255)',
                ...(column.columnDef.required && {
                    '&::after': {
                        content: '"*"',
                        color: 'red',
                        marginLeft: '30px',
                        position: 'absolute',
                    }
                })
            }
        }),
        muiRowDragHandleProps: ({ table }) => ({
            onDragEnd: () => {
                const { draggingRow, hoveredRow } = table.getState();
                if (hoveredRow && draggingRow) {
                    tabledata.splice(
                        hoveredRow.index,
                        0,
                        tabledata.splice(draggingRow.index, 1)[0],
                    );
                    setTabledata([...tabledata]);
                }
            },
        }),
        enableRowNumbers: true,
        rowNumberDisplayMode: 'static', // 显示原始行号
        renderTopToolbarCustomActions: ({ table }) => (
            <Box sx={{ display: 'flex', gap: '1rem', p: '4px' }}>
                <Button
                    // color="primary"
                    onClick={() => {
                        setOpenDrawer(true); // 打开抽屉
                        productsGet(); // 获取商品库数据
                    }}
                    variant="contained"
                    sx={{
                        backgroundColor: 'rgb(74, 146, 243)',
                    }}
                    disabled={isloacked}
                >
                    从合同选取
                </Button>
                <Button
                    // color="primary"
                    onClick={async () => {
                        await handleSave(); // 保存数据
                    }}
                    variant="contained"
                    sx={{
                        backgroundColor: 'rgb(74, 146, 243)',
                    }}
                    disabled={isloacked}
                >
                    保存
                </Button>
                <Button
                    onClick={() => {
                        window.ZOHO.CRM.UI.Popup.close();
                    }}
                    variant="outlined"
                >
                    取消
                </Button>
            </Box>
        ),
        enableRowActions: true,
        displayColumnDefOptions: {
            'mrt-row-actions': {
                header: '操作',  // 设置表头为“操作”
                size: 4,  // 设置列宽
            },
            'mrt-row-drag': {
                header: '',  // 设置表头为“操作”
                size: 4,  // 设置列宽
            },
        },
        renderRowActions: ({ row, table }) => (
            <Box>
                <Clear onClick={() => {
                    if (!isloacked) {
                        tabledata.splice(row.index, 1); //assuming simple data table
                        setTabledata([...tabledata]);
                        // setTabledata((prevRecords) => prevRecords.filter((record) => record.id !== row.id)); // 从记录中移除当前行
                    }
                }}>
                </Clear>

            </Box>
        ),
        enableStickyFooter: true, // 启用粘性页脚
        // muiEditTextFieldProps: ({ cell }) => ({
        //   onBlur: (event) => {
        //     handleSaveCell(cell, event.target.value); // 在失焦时保存
        //   },
        // }),
        renderToolbarInternalActions: ({ table }) => (
            <Box>
                <IconButton
                    onClick={() => {
                        exportToExcel(tabledata, columns);
                    }}
                >
                    <GetAppOutlined />
                </IconButton>
                <ShowHideColumnsButton table={table} />
            </Box>
        ),
        enableKeyboardShortcuts: false,
        defaultColumn: {
            muiTableBodyCellProps: ({ row, cell }) => ({
                onKeyDown: (event) => { // 添加键盘事件监听
                    if (event.key === 'Enter') {
                        const nextrownum = row.index + 1; // 获取下一行的索引
                        const currentIndex = cell.column.getIndex();
                        if (nextrownum < tabledata.length) {
                            const nextRow = document.querySelector(
                                `tr[data-index="${nextrownum}"]`
                            );

                            // 在该行中找到对应列的单元格
                            if (nextRow) {
                                const nextCell = nextRow.querySelector(
                                    `td[data-index="${currentIndex}"]`
                                );
                                if (nextCell) {
                                    nextCell.focus();
                                    const dblClickEvent = new MouseEvent('dblclick', {
                                        bubbles: true,
                                        cancelable: true,
                                        view: window
                                    });
                                    nextCell.dispatchEvent(dblClickEvent);
                                }
                            }
                        }
                    }
                },
                tabIndex: 0,
            })
        },
    });


    //选择配置
    const table_product = useMaterialReactTable({
        columns: columns_product,
        data: productdata || [],
        enableRowNumbers: true, // 启用行号
        enablePagination: false, // 禁用分页
        enableColumnResizing: true, // 启用列调整大小
        enableStickyHeader: true, // 启用粘性表头
        enableDensityToggle: false, // 禁用密度切换
        enableGlobalFilter: false, // 禁用全局过滤
        localization: LocalizationZH, // 设置中文
        state: {
            rowSelection, // 设置行选择状态
            isLoading: loadingptable,     // 设置加载状态
        },
        enableFullScreenToggle: false, // 禁用全屏按钮
        enableColumnPinning: true, // 启用列固定
        getRowId: (row) => row.id, // 设置每行的唯一标识
        // rowPinningDisplayMode: 'select-sticky', // 设置行固定显示模式为选择固定
        positionToolbarAlertBanner: 'bottom',   // 将工具栏警告横幅的位置设置为底部
        initialState: {
            density: 'compact',
            columnPinning: { left: ['mrt-row-select', 'mrt-row-numbers', 'Subject', 'AccountOrderNo', 'pname', 'AccountprtNo'] },
            pagination: { pageSize: 30, },
            showColumnFilters: true, // 显示列过滤器
            columnVisibility: { Lengthofouterbox: false, Cartonwidth: false, Heightofouterbox: false, Volume: false, Netweightofinnebox: false, Nuofboxesinpg: false, Nuofboxeinnerbox: false, Packagingquantityperpg: false, Netweight: false, Grossweight: false, Packaginunit: false, Declarationelements: false, HSCode_text: false, }
        },
        muiTableContainerProps: {
            sx: {
                minHeight: '80vh', // 这里设置表格最大高度
                maxHeight: '80vh', // 这里设置表格最大高度
                overflowY: 'auto',  // 启用竖向滚动条
                overflowX: 'auto',  // 启用横向滚动条，横向滚动条默认显示
            },
        },
        // enableRowNumbers: true,
        // rowNumberDisplayMode: 'static', // 显示原始行号
        // enableRowSelection: true,   // 启用行选择
        enableRowSelection: (row) => ((row.original.PSQty || 0) < row.original.Quantity && !row.original.selected) || ['费用类'].includes(row.original.Category), //enable row selection conditionally per row&& !row.original.selected, //enable row selection conditionally per row
        onRowSelectionChange: setRowSelection, // 当行选择发生变化时，更新行选择状态
        renderTopToolbarCustomActions: ({ table }) => (
            <Box sx={{ display: 'flex', gap: '1rem', p: '4px' }}>
                <Button
                    onClick={() => {
                        console.log(rowSelection);
                        // 从选中的行中提取产品信息
                        const selectedProductIds = Object.keys(rowSelection).filter((key) => rowSelection[key]); // 获取选中的产品 ID
                        const selectedProducts = selectedProductIds.map((id) => {
                            const selectedRow = productdata.find((product) => product.id === id); // 获取选中的产品
                            return selectedRow; // 返回选中的产品信息
                        }).filter(Boolean); // 过滤掉未找到的产品

                        console.log('selectedProducts', selectedProducts);

                        let resultarray = [];
                        selectedProducts.forEach((product) => {
                            const findedProduct = tabledata.find((item) => item.id1 === product.id);
                            if (!findedProduct) {
                                let boxnum = (product?.Quantity - (product?.PSQty || 0)) / (product?.Packagingquantityperpg || 1);
                                resultarray.push({
                                    Product: { id: product?.pdid, name: product?.pname },// 产品信息
                                    AccountprtNo: product?.AccountprtNo,
                                    Subject: product?.Subject,
                                    AccountOrderNo: product?.AccountOrderNo,
                                    ShippingMark: product?.ShippingMark,
                                    internalcode: product?.internalcode,
                                    Englishname: product?.Englishname,
                                    Specification: product?.Specification,
                                    // List_Price: product?.List_Price,
                                    // Discount: product?.Discount,
                                    PSQty: product?.PSQty,
                                    Quantity: product?.Quantity,
                                    NumberofCartons: product?.NumberofCartons,
                                    Quantity_unused: product?.Quantity - (product?.PSQty || 0), //可用数量 = 总数量 - 已分配数量
                                    PurchaseQty: product?.Quantity - (product?.PSQty || 0),  //数量
                                    PackQty: boxnum,   //箱数
                                    TotalVolume: (boxnum * product?.Volume).toFixed(4), //体积
                                    TotalGrossweight: (boxnum * product?.Grossweight).toFixed(4), //毛重,
                                    TotalNetweight: (boxnum * product?.Netweight).toFixed(4), //净重
                                    PurchaseAmount: (product?.Quantity - (product?.PSQty || 0)) * product?.Purchaseunitprice, //金额
                                    Packagingquantityperpg: product?.Packagingquantityperpg,
                                    Purchaseunitprice: product?.Purchaseunitprice,
                                    Unit: product?.Unit,
                                    Volume: product?.Volume,
                                    Make: product?.Brand,
                                    Nuofboxesinpg: product?.Nuofboxesinpg,
                                    Nuofboxeinnerbox: product?.Nuofboxeinnerbox,
                                    Lengthofouterbox: product?.Lengthofouterbox,
                                    Cartonwidth: product?.Cartonwidth,
                                    Heightofouterbox: product?.Heightofouterbox,
                                    Netweight: product?.Netweight,
                                    Grossweight: product?.Grossweight,
                                    Productname: product?.Productname,
                                    ChinesePackagedesp: product?.ChinesePackagedesp,
                                    Chinesespecification: product?.Chinesespecification,
                                    // Chineseingredients: product?.Chineseingredients,
                                    Chptrequirements_material: product?.Chptrequirements_material,
                                    Category: product?.Category,
                                    Packaginunit: product?.Packaginunit,
                                    HSCode: product?.HSCode,
                                    id1: product?.id,
                                    SalesOrderId: product?.pid,
                                });
                            }
                        })


                        // console.log(resultarray);

                        // 将选中的产品添加到主表中
                        setTabledata((prevData) => [...prevData, ...resultarray]);

                        // 可选：清空行选择状态
                        setRowSelection({});
                        setOpenDrawer(false); // 关闭抽屉组件

                    }}
                    variant="contained"
                    sx={{
                        backgroundColor: 'rgb(74, 146, 243)', // 背景颜色设置为白色
                    }}
                >
                    确定
                </Button>
                <Button
                    onClick={() => {
                        setOpenDrawer(false); // 关闭抽屉组件
                    }}
                    variant="contained"
                    sx={{
                        backgroundColor: '#ffffff', // 背景颜色设置为白色
                        color: '#000000', // 字体颜色设置为黑色
                    }}
                >
                    关闭窗口
                </Button>
            </Box>
        ),
    });

    return (
        <>
            <div>
                {loading ? (
                    <Box
                        sx={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            height: '100vh' // 使加载图标在页面中央
                        }}
                    >
                        <CircularProgress />
                    </Box>
                ) : (
                    <>
                        <MaterialReactTable
                            table={table} />
                    </>
                )}
            </div>
            {/* 抽屉组件 */}
            <Drawer
                anchor="left"
                open={openDrawer}
                sx={{ width: '75vw', zIndex: 1300 }}
            >
                <Box sx={{ width: '75vw', padding: '2px' }}>
                    <MaterialReactTable
                        table={table_product}
                    />
                </Box>
            </Drawer >
        </>
    );



}



export default App;